package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
	"net/http"
)

var searcher *xdb.Searcher

func InitXdb() {
	dbPath := "data/ip2region.xdb"
	// 1、从 dbPath 加载整个 xdb 到内存
	cBuff, err := xdb.LoadContentFromFile(dbPath)
	if err != nil {
		fmt.Printf("failed to load content from `%s`: %s\n", dbPath, err)
		panic(err)
		return
	}

	// 2、用全局的 cBuff 创建完全基于内存的查询对象。
	s, err := xdb.NewWithBuffer(cBuff)
	if err != nil {
		fmt.Printf("failed to create searcher with content: %s\n", err)
		panic(err)
		return
	}
	searcher = s
}

func Index(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", nil)
}

func Ip(c *gin.Context) {
	c.HTML(http.StatusOK, "ip.html", nil)
}

func ApiIp(c *gin.Context) {
	ip := c.Query("ip")
	region, err := searcher.SearchByStr(ip)
	if err != nil {
		c.JSON(500, gin.H{
			"message": err.Error(),
		})
		return
	}
	c.JSON(200, gin.H{
		"region": region,
	})
}

func ClientIp(c *gin.Context) {
	ip := c.ClientIP()
	region, err := searcher.SearchByStr(ip)
	if err != nil {
		c.JSON(500, gin.H{
			"message": err.Error(),
		})
		return
	}
	c.JSON(200, gin.H{
		"ip":     ip,
		"region": region,
	})
}

func Color(c *gin.Context) {
	c.HTML(http.StatusOK, "color.html", nil)
}

func Base64(c *gin.Context) {
	c.HTML(http.StatusOK, "base64.html", nil)
}

func Image2Base64(c *gin.Context) {
	c.HTML(http.StatusOK, "image2base64.html", nil)
}

func TinyImage(c *gin.Context) {
	c.HTML(http.StatusOK, "tinyimg.html", nil)
}

func Hash(c *gin.Context) {
	c.HTML(http.StatusOK, "hash.html", nil)
}

func FileHash(c *gin.Context) {
	c.HTML(http.StatusOK, "file_hash.html", nil)
}

func JSONView(c *gin.Context) {
	c.HTML(http.StatusOK, "json.html", nil)
}

func Number(c *gin.Context) {
	c.HTML(http.StatusOK, "number.html", nil)
}

func QRCode(c *gin.Context) {
	c.HTML(http.StatusOK, "qrcode.html", nil)
}

func Regex(c *gin.Context) {
	c.HTML(http.StatusOK, "regex.html", nil)
}

func Timestamp(c *gin.Context) {
	c.HTML(http.StatusOK, "timestamp.html", nil)
}

func WebSocket(c *gin.Context) {
	c.HTML(http.StatusOK, "websocket.html", nil)
}

func AES(c *gin.Context) {
	c.HTML(http.StatusOK, "aes.html", nil)
}

func DES(c *gin.Context) {
	c.HTML(http.StatusOK, "des.html", nil)
}

func RSA(c *gin.Context) {
	c.HTML(http.StatusOK, "rsa.html", nil)
}

func Morse(c *gin.Context) {
	c.HTML(http.StatusOK, "morse.html", nil)
}

func URL(c *gin.Context) {
	c.HTML(http.StatusOK, "url.html", nil)
}

func Unicode(c *gin.Context) {
	c.HTML(http.StatusOK, "unicode.html", nil)
}

func JSON2GO(c *gin.Context) {
	c.HTML(http.StatusOK, "json2go.html", nil)
}

func JSON2XML(c *gin.Context) {
	c.HTML(http.StatusOK, "json2xml.html", nil)
}

func JSON2YAML(c *gin.Context) {
	c.HTML(http.StatusOK, "json2yaml.html", nil)
}

func PDF2IMG(c *gin.Context) {
	c.HTML(http.StatusOK, "pdf2img.html", nil)
}
